package com.lanou3g.musicenjoy.activities;

import android.app.AlarmManager;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;

import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;

import android.widget.EditText;

import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lanou3g.musicenjoy.R;
import com.lanou3g.musicenjoy.application.MusicApplication;
import com.lanou3g.musicenjoy.entity.PlayMusicEntity;
import com.lanou3g.musicenjoy.entity.Recommendation;
import com.lanou3g.musicenjoy.entity.SingerEntity;
import com.lanou3g.musicenjoy.entity.Special;
import com.lanou3g.musicenjoy.eventbus.MyEvent;
import com.lanou3g.musicenjoy.fragment.HotSingerFragment;
import com.lanou3g.musicenjoy.fragment.MainFragment;
import com.lanou3g.musicenjoy.fragment.NewLeftFragment;
import com.lanou3g.musicenjoy.fragment.SpecialActivityFragment;
import com.lanou3g.musicenjoy.service.DownloadServices;
import com.lanou3g.musicenjoy.service.OnlineService;
import com.lanou3g.musicenjoy.utils.Time;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import de.hdodenhof.circleimageview.CircleImageView;


/**
 * Created by 辛鑫 on 15/10/20.
 * mainActivity,fragment的容器
 */
public class HelloDrawerActivity extends FragmentActivity implements View.OnClickListener {

    public static final String ALARM_CLOCK_BROADCAST = "alarm_clock_broadcast";
    private int mScreenWidth;
    private Button okBtn;
    private Button cancleBtn;
    private EditText timeEt;


    @Bind(R.id.song_img)
    CircleImageView songImg;
    @Bind(R.id.main_song_name)
    TextView mainSongName;
    @Bind(R.id.main_singer_name)
    TextView mainSingerName;
    @Bind(R.id.main_play_next_btn)
    ImageView mainPlayNextBtn;
    @Bind(R.id.main_play_btn)
    ImageButton mainPlayBtn;
    @Bind(R.id.below_layout)
    RelativeLayout belowLayout;
    private List<PlayMusicEntity> data;
    //activity与service绑定成功之后的桥梁对象
    private OnlineService.MediaBinder mediaBinder;
    private int currentPosition;
    private int count;
    //0:播放 1:暂停
    private int[] startBtn = {R.mipmap.img_appwidget91_voice_pause_normal,
            R.mipmap.img_appwidget91_voice_play_normal};

    //定义一个ServiceConnection连接
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.i("000", "连接成功");
            mediaBinder = (OnlineService.MediaBinder) service;

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i("汪", "连接失败");
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i("000", "oncreate");
        setContentView(R.layout.main_activity);
        data = new ArrayList<>();
        ButterKnife.bind(this);
        Log.i("转码", Time.formatTime((long) 0));

        //订阅
        EventBus.getDefault().register(this);
        mainPlayBtn.setOnClickListener(this);
        mainPlayNextBtn.setOnClickListener(this);
        belowLayout.setOnClickListener(this);

        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.container, new MainFragment())
                .commit();

        //绑定service
        Intent intent = new Intent(this, OnlineService.class);
        bindService(intent, connection, BIND_AUTO_CREATE);


        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        mScreenWidth = metric.widthPixels;
        //过滤
        IntentFilter filter = new IntentFilter();
        filter.addAction(ALARM_CLOCK_BROADCAST);
        //订阅广播
        registerReceiver(mAlarmReceiver, filter);

    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (mediaBinder.isPlaying()) {
            mainPlayBtn.setImageResource(startBtn[0]);
        } else if (!mediaBinder.isPlaying() && mediaBinder.getDuration() > mediaBinder.getCurrentPosition()) {
            mainPlayBtn.setImageResource(startBtn[1]);
        }
    }


    //接受从服务传递过来的数据

    public void onEvent(MyEvent.Isplay event) {
        setData();
        mainPlayBtn.setImageResource(startBtn[0]);
    }

    //一首歌曲自动播放完成时接受消息
    public void onEvent(MyEvent.AutoNext evevnt) {
        setData();
    }

    //接受播放页面点击下一首时的通知,设置数据
    public void onEvent(MyEvent.IsNext event) {
        setData();
    }

    //接受顺序播放完成最后一首时的通知
    public void onEvent(MyEvent.IsFinish event) {
        mainPlayBtn.setImageResource(startBtn[1]);
    }
    // 设置歌曲相关内容
    private void setData() {
        if (mediaBinder != null && mediaBinder.getSingerName() != null) {
            mainSingerName.setText(mediaBinder.getSingerName());
            mainSongName.setText(mediaBinder.getSongName());
            if (mediaBinder.getPicture() != null) {
                Picasso.with(this).load(mediaBinder.getPicture()).into(songImg);
            } else {
                Picasso.with(this).load(R.mipmap.music).into(songImg);
            }
        }

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.main_play_next_btn:
                mediaBinder.nextSong();

                if (currentPosition == (data.size() - 1)) {
                    currentPosition = 0;

                } else {
                    currentPosition++;
                }

                setData();
                break;
            case R.id.below_layout:
                Log.i("BEL", "点击了下标题");
                Intent intent = new Intent(this, PlayerActivity.class);
                startActivity(intent);
                //动画效果
                overridePendingTransition(R.anim.slide_in_bottom, R.anim.slide_out_top);
                break;
            case R.id.main_play_btn:
                if (mediaBinder.isPlaying()) {
                    Log.i("ssss", "开始播放");
                    mainPlayBtn.setImageResource(startBtn[1]);
                    Toast.makeText(HelloDrawerActivity.this, "已暂停", Toast.LENGTH_SHORT).show();
                    mediaBinder.pause();
                } else if (!mediaBinder.isPlaying() && mediaBinder.getDuration() > mediaBinder.getCurrentPosition()) {
                    Log.i("ssss", "进入该方法");
                    mainPlayBtn.setImageResource(startBtn[0]);
                    Toast.makeText(HelloDrawerActivity.this, "正在播放", Toast.LENGTH_SHORT).show();
                    mediaBinder.start();
                } else {
                    Log.i("ssss", "打印log");
                    Toast.makeText(HelloDrawerActivity.this, "请选择要播放的歌曲", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    //乐库-推荐轮播
    public void skepFrament(int position, List<Recommendation.PicEntity> datas) {

        Bundle bundle = new Bundle();
        if (datas != null) {

            Log.i("111111000",datas.get(position%datas.size()).getType()+"");
            if (datas.get(position%datas.size()).getType()==7) {
                NewLeftFragment fragment = new NewLeftFragment();
                String url = datas.get(position % datas.size()).getRandpic_iphone6();
                Log.i("dfjas", url);
                String id = datas.get(position % datas.size()).getCode();
                bundle.putString("url", url);
                bundle.putString("id", id);
                fragment.setArguments(bundle);
                getSupportFragmentManager()
                        .beginTransaction()
                        .addToBackStack(null)
                        .replace(R.id.container, fragment)
                        .commit();
            }


        }
    }

    //乐库歌手轮播
    public void recycleFragment(int position, List<SingerEntity.ArtistEntity> datas) {
        HotSingerFragment hotSingerFragment = new HotSingerFragment();
        Bundle bundle = new Bundle();
        if (datas != null) {
            String url = datas.get(position % datas.size()).getAvatar_big();
            String id = datas.get(position % datas.size()).getTing_uid();
            Log.i("rrr", url + "999");
            bundle.putString("url", url);
            bundle.putString("id", id);
            hotSingerFragment.setArguments(bundle);
            getSupportFragmentManager()
                    .beginTransaction()
                    .addToBackStack(null)
                    .replace(R.id.container, hotSingerFragment)
                    .commit();
        }
    }

    //乐库-歌手-infor-recycleview
    public void intentRecycleView(int position, List<Special.AlbumlistEntity> datas) {
        SpecialActivityFragment fragment = new SpecialActivityFragment();
        Bundle bundle = new Bundle();
        String b = datas.get(position).getAlbum_id();
        String time = datas.get(position).getPublishtime();
        String url = datas.get(position).getPic_radio();
        bundle.putString("b", b);
        bundle.putString("time", time);
        bundle.putString("url", url);

        fragment.setArguments(bundle);
        getFragmentManager()
                .beginTransaction()
                .addToBackStack(null)
                .replace(R.id.container, fragment)
                .commit();


    }


    public void showSleepDialog() {

        if (MusicApplication.mIsSleepClockSetting) {
            cancleSleepClock();
            Toast.makeText(getApplicationContext(), "已取睡眠模式！",
                    Toast.LENGTH_SHORT).show();
            return;
        }

        View view = View.inflate(this, R.layout.sleep_time, null);

        final Dialog dialog = new Dialog(this, R.style.lrc_dialog);
        dialog.setContentView(view);
        dialog.setCanceledOnTouchOutside(false);

        Window dialogWindow = dialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.CENTER);
        // lp.x = 100; // 新位置X坐标
        // lp.y = 100; // 新位置Y坐标
        lp.width = (int) (mScreenWidth * 0.7); // 宽度
        // lp.height = 400; // 高度

        // 当Window的Attributes改变时系统会调用此函数,可以直接调用以应用上面对窗口参数的更改,也可以用setAttributes
        // dialog.onWindowAttributesChanged(lp);
        dialogWindow.setAttributes(lp);

        dialog.show();


        cancleBtn = (Button) view.findViewById(R.id.cancle_btn);
        okBtn = (Button) view.findViewById(R.id.ok_btn);
        timeEt= (EditText) view.findViewById(R.id.time_et);
        okBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String timeS = timeEt.getText().toString();
                if (TextUtils.isEmpty(timeS)
                        || Integer.parseInt(timeS) == 0) {
                    Toast.makeText(getApplicationContext(), "输入无效！",
                            Toast.LENGTH_SHORT).show();
                }
                setSleepClock(timeS);
                dialog.dismiss();
            }
        });
        cancleBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

    }

    /**
     * 设置睡眠闹钟
     *
     * @param timeS
     */
    private void setSleepClock(String timeS) {
        Intent intent = new Intent(ALARM_CLOCK_BROADCAST);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                this, 0, intent, 0);
        // 设置time时间之后退出程序
        int time = Integer.parseInt(timeS);
        long longTime = time * 60 * 1000L;
        AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        am.set(AlarmManager.RTC, System.currentTimeMillis() + longTime,
                pendingIntent);
        MusicApplication.mIsSleepClockSetting = true;
        Toast.makeText(getApplicationContext(), "将在" + timeS + "分钟后退出软件", Toast.LENGTH_SHORT)
                .show();
    }

    /**
     * 取消睡眠闹钟
     */
    private void cancleSleepClock() {
        Intent intent = new Intent(ALARM_CLOCK_BROADCAST);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                this, 0, intent, 0);
        AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        am.cancel(pendingIntent);
        MusicApplication.mIsSleepClockSetting = false;
    }

    private BroadcastReceiver mAlarmReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            //退出程序
            finish();
        }

    };


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mAlarmReceiver);
        //取消订阅
        EventBus.getDefault().unregister(this);
        //解除绑定
        unbindService(connection);
        mediaBinder = null;
    }

    //获得从列表中传过来的数据
    public void onEvent(MyEvent.DownlaodData event) {
        count++;
        startDownloadService(count, event.getUrl(), event.getSongName(), event.getPicUrl());

    }

    public void startDownloadService(int count, String url, String title, String imgUrl) {
        //启动服务,将网址和位置传递到服务中
        Intent i = new Intent(this, DownloadServices.class);
        i.putExtra("url", url);
        i.putExtra("notifyId", count);
        i.putExtra("title", title);
        i.putExtra("picUrl", imgUrl);
        Log.i("nnnn", url + "0");
        Log.i("nnnn", title + "1");
        Log.i("nnnn", imgUrl + "2");
        startService(i);
    }
}
